package login_tool

import (
	"context"
	"fmt"
	"net/http"

	"golang.org/x/oauth2"
)

// Provider 需要为每个第三方身份验证提供者实现
type Provider interface {
	Name() string
	SetName(name string)
	BeginAuth(state string) (Session, error)
	UnmarshalSession(string) (Session, error)
	FetchUser(Session) (User, error)
	RefreshToken(refreshToken string) (*oauth2.Token, error)
	RefreshTokenAvailable() bool
	EmptySession(accessToken string) Session
}

const NoAuthUrlErrorMessage = "an AuthURL has not been set"

// Providers 存放多种登录实现类
type Providers map[string]Provider

var providers = Providers{}

// UseProviders 添加可用登录提供者列表.
func UseProviders(viders ...Provider) {
	for _, provider := range viders {
		providers[provider.Name()] = provider
	}
}

// GetProviders 返回当前正在使用的所有提供程序的列表
func GetProviders() Providers {
	return providers
}

// GetProvider 根据提供者名称获取实现类
func GetProvider(name string) (Provider, error) {
	provider := providers[name]
	if provider == nil {
		return nil, fmt.Errorf("no provider for %s exists", name)
	}
	return provider, nil
}

// ContextForClient 提供与oauth2一起使用的上下文
func ContextForClient(h *http.Client) context.Context {
	if h == nil {
		return oauth2.NoContext
	}
	return context.WithValue(oauth2.NoContext, oauth2.HTTPClient, h)
}

func HTTPClientWithFallBack(h *http.Client) *http.Client {
	if h != nil {
		return h
	}
	return http.DefaultClient
}
